/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2010>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Serialization;
using MyPhotoIndex.Utilities;

namespace MyPhotoIndex.Plugins.Share.Facebook.Fb_API
{
    public class ImageUploader
    {
        public event EventHandler<ProgressEventArgs> ImageUploadEvent;

        private const string FACEBOOK_HTTP_URI = "http://api.facebook.com/bestserver.php";

        Authentication m_authentication;

        public ImageUploader(Authentication authentication)
        {
            m_authentication = authentication;
        }

        public bool Upload(String fileName, String caption, List<String> tags, String albumId)
        {
            HttpWebRequest request = HttpWebRequest.Create(FACEBOOK_HTTP_URI) as HttpWebRequest;
            RequestBuilder requestBuilder = new RequestBuilder(m_authentication.ApiKey, m_authentication.Secret);
            requestBuilder.BlobReadProgressEvent += new EventHandler<ProgressEventArgs>(requestBuilder_BlobReadProgressEvent);
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    if (String.IsNullOrEmpty(caption) == false)
                    {
                        requestBuilder.Add("caption", caption);
                    }

                    if (String.IsNullOrEmpty(albumId) == false)
                    {
                        requestBuilder.Add("aid", albumId);
                    }
   
                    requestBuilder.SetBlobParameter(Path.GetFileNameWithoutExtension(fileName), fs, "image/jpeg");
                    requestBuilder.InitializeRequest(request, "facebook.photos.upload", m_authentication.SessionKey, true);

                    String responseData = String.Empty;
                    WebResponse response = request.GetResponse();
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream);
                        responseData = reader.ReadToEnd();
                    }

                    XmlSerializer serializer = new XmlSerializer(typeof(photos_upload_response));
                    photos_upload_response uploadResponse = (photos_upload_response)serializer.Deserialize(new StringReader(responseData));

                    if (String.IsNullOrEmpty(uploadResponse.created))
                    {
                        return false;
                    }

                    if (tags != null &&
                        tags.Count > 0)
                    {
                        SetTags(uploadResponse.pid, tags);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }

                return false;
            }
        }

        void requestBuilder_BlobReadProgressEvent(object sender, ProgressEventArgs e)
        {
            if (ImageUploadEvent != null)
            {
                ImageUploadEvent.Invoke(this, e);
            }
        }

        private const String JSON_TAG_FORMAT = "{{\"x\":\"{0}.0\",\"y\":\"{1}.0\",\"tag_text\":\"{2}\"}}";

        private void SetTags(String photoId, List<String> tags)
        {
            HttpWebRequest request = HttpWebRequest.Create(FACEBOOK_HTTP_URI) as HttpWebRequest;
            RequestBuilder requestBuilder = new RequestBuilder(m_authentication.ApiKey, m_authentication.Secret);

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("[");
                int x = 0, y = 0;
                foreach (String tag in tags)
                {
                  //  x++; y++;
                    sb.Append(String.Format(JSON_TAG_FORMAT, x, y, tag.Replace("\"", "")));
                    sb.Append(",");
                }

                sb.Remove(sb.Length - 1, 1);
                sb.Append("]");

                String tagsData = sb.ToString();

                requestBuilder.Add("pid", photoId);
                requestBuilder.Add("tags", tagsData);
                requestBuilder.InitializeRequest(request, "facebook.photos.addTag", m_authentication.SessionKey, true);

                String responseData = String.Empty;
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream);
                    responseData = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
    }
}
